<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 修改后 -->
      <el-form-item label="老人姓名" prop="elderlyName">
        <el-input
          v-model="queryParams.elderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同期限" prop="contractDateRange">
        <el-date-picker
          clearable
          v-model="queryParams.contractDateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item style="width: 262px" label="合同状态" prop="contractStatus">
        <el-select
          v-model="queryParams.contractStatus"
          placeholder="请选择合同状态"
          clearable
        >
          <el-option
            v-for="dict in contract_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['le:contract:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['le:contract:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['le:contract:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['le:contract:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="contractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="老人姓名" align="center" prop="elderlyId">
        <template #default="scope">
          <span v-for="item in elderlyList" :key="item.id">
            <span v-if="item.id == scope.row.elderlyId">{{ item.name }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="老人身份证" align="center" prop="elderlyId">
        <template #default="scope">
          <span v-for="item in elderlyList" :key="item.id">
            <span v-if="item.id == scope.row.elderlyId">{{ item.idCard }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="合同期限" align="center" width="220">
        <template #default="scope">
          <span
            >{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }} ——
            {{ parseTime(scope.row.endDate, "{y}-{m}-{d}") }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="contractStatus">
        <template #default="scope">
          <div
            :class="[
              'contract-status-tag',
              'contract-status-' + scope.row.contractStatus,
            ]"
          >
            {{ scope.row.contractStatus }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator">
        <template #default="scope">
          <span v-for="item in userList" :key="item.userId">
            <span v-if="item.userId == scope.row.creator">{{
              item.userName
            }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- 原操作列替换为以下内容 -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Search"
            @click="handleView(scope.row)"
            v-hasPermi="['le:contract:query']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同跟踪对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="contractRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="老人外键编号" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
        <el-form-item label="合同期限开始时间" prop="startDate">
          <el-date-picker
            clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择合同期限开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同期限结束时间" prop="endDate">
          <el-date-picker
            clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择合同期限结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同状态" prop="contractStatus">
          <el-radio-group v-model="form.contractStatus">
            <el-radio
              v-for="dict in contract_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="签约时间" prop="signTime">
          <el-date-picker
            clearable
            v-model="form.signTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择签约时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同文件" prop="contractFile">
          <file-upload v-model="form.contractFile" />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="丙方姓名" prop="partyCName">
          <el-input v-model="form.partyCName" placeholder="请输入丙方姓名" />
        </el-form-item>
        <el-form-item label="丙方联系电话" prop="partyCPhone">
          <el-input
            v-model="form.partyCPhone"
            placeholder="请输入丙方联系电话"
          />
        </el-form-item>
        <el-form-item label="解除提交人" prop="terminationSubmitter">
          <el-input
            v-model="form.terminationSubmitter"
            placeholder="请输入解除提交人"
          />
        </el-form-item>
        <el-form-item label="解除时间" prop="terminationTime">
          <el-date-picker
            clearable
            v-model="form.terminationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择解除时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contract">
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
} from "@/api/le/contract";
import { listElderly } from "@/api/le/elderly";
import { listUser } from "@/api/system/user";

import { get } from "@vueuse/core";
import { useRouter } from "vue-router";
const router = useRouter();

// 点击“查看”跳转详情页
function handleView(row) {
  router.push({ path: `/contract/detail/${row.id}` });
}
//获取用户信息列表
const userList = ref([]);
const getUserList = () => {
  listUser({ pageNum: 1, pageSize: 9999 }).then((response) => {
    console.log(response);
    userList.value = response.rows;
  });
};
//获取老人信息列表
const elderlyList = ref([]);
const getElderlyList = () => {
  listElderly({ pageNum: 1, pageSize: 9999 }).then((response) => {
    elderlyList.value = response.rows;
  });
};
const { proxy } = getCurrentInstance();
const { contract_status } = proxy.useDict("contract_status");

const contractList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: null,
    elderlyId: null,
    startDate: null,
    endDate: null,
    contractDateRange: [], // 新增：绑定日期范围选择器
    contractStatus: null,
    elderlyName: null, // 新增：老人姓名模糊查询参数
  },
  rules: {
    contractName: [
      { required: true, message: "合同名称不能为空", trigger: "blur" },
    ],
    contractNo: [
      { required: true, message: "合同编号不能为空", trigger: "blur" },
    ],
    elderlyId: [
      { required: true, message: "老人外键编号不能为空", trigger: "blur" },
    ],
    startDate: [
      { required: true, message: "合同期限开始时间不能为空", trigger: "blur" },
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

function getList() {
  loading.value = true;
  // 组装请求参数：拆分日期范围 + 携带老人姓名模糊查询参数
  const requestParams = {
    ...queryParams.value,
    startDate: queryParams.value.contractDateRange?.[0] || null,
    endDate: queryParams.value.contractDateRange?.[1] || null,
    elderlyName: queryParams.value.elderlyName || null, // 新增：老人姓名模糊查询参数
  };
  // 移除不需要的临时字段
  delete requestParams.contractDateRange;

  listContract(requestParams).then((response) => {
    const processedContracts = response.rows.map((item) => {
      const status = calculateContractStatus(
        item.startDate,
        item.endDate,
        item.terminationTime
      );
      return { ...item, contractStatus: status };
    });
    contractList.value = processedContracts;
    total.value = response.total;
    loading.value = false;
  });
}
// 计算合同状态
function calculateContractStatus(startDate, endDate, terminationTime) {
  const now = new Date();
  const start = new Date(startDate);
  const end = new Date(endDate);

  // 已失效（已解除的合同，若有解除时间则直接判定）
  if (terminationTime) {
    return "已失效";
  }
  // 未生效：当前时间 < 合同开始时间
  if (now < start) {
    return "未生效";
  }
  // 生效中：合同结束时间 > 当前时间 >= 合同开始时间
  else if (now >= start && now < end) {
    return "生效中";
  }
  // 已过期：当前时间 >= 合同结束时间
  else if (now >= end) {
    return "已过期";
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    contractName: null,
    contractNo: null,
    elderlyId: null,
    startDate: null,
    endDate: null,
    contractStatus: null,
    signTime: null,
    contractFile: null,
    creator: null,
    createTime: null,
    partyCName: null,
    partyCPhone: null,
    terminationSubmitter: null,
    terminationTime: null,
    terminationAgreement: null,
    checkInManagementId: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("contractRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加合同跟踪";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getContract(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改合同跟踪";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contractRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateContract(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addContract(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除合同跟踪编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delContract(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "le/contract/export",
    {
      ...queryParams.value,
    },
    `contract_${new Date().getTime()}.xlsx`
  );
}

getList();
getElderlyList();
getUserList();
</script>
<style scoped>
/* 合同状态通用样式 */
.contract-status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid;
  font-size: 12px;
}

/* 未生效（蓝色系） */
.contract-status-未生效 {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

/* 生效中（绿色系） */
.contract-status-生效中 {
  border-color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

/* 已失效（红色系） */
.contract-status-已失效 {
  border-color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

/* 已过期（橙色系） */
.contract-status-已过期 {
  border-color: #e6a23c;
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}
</style>
